package com.action.gulimall.ware.listener;

import com.action.common.constant.MqConstant;
import com.action.common.to.mq.OrderTo;
import com.action.common.to.mq.StockLockedTo;
import com.action.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.action.gulimall.ware.entity.WareOrderTaskEntity;
import com.action.gulimall.ware.service.WareOrderTaskDetailService;
import com.action.gulimall.ware.service.WareOrderTaskService;
import com.action.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author sl shilun217@qq.com
 * @Deacription 订单库存锁定释放消息消费
 * @date 2021/07/04/11:30
 **/
@Slf4j
@RabbitListener(queues = {MqConstant.ORDER_STOCK_RELEASE_QUEUE_NAME})
@Component
public class StockListener{

    @Autowired
    WareSkuService wareSkuService;
    @RabbitHandler
    public void releaseStock(Message message, StockLockedTo stockLockedTo, Channel channel) throws IOException {
        try {
            log.info("******收到解锁库存的消息******");
            //进行库存解锁
            wareSkuService.unLockStock(stockLockedTo);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("进行库存解锁wareSkuService.unLockStock执行异常", e);
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

    //订单超时 取消时解锁库存
    @RabbitHandler
    public void releaseStock(Message message, OrderTo orderTo, Channel channel) throws IOException {
        try {
            log.info("******收到解锁库存的消息******");
            //进行库存解锁
            wareSkuService.unLockStock(orderTo);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("进行库存解锁wareSkuService.unLockStock执行异常", e);
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
